<template>
  <div class="product-manager-warp disabled-warp" style="height: calc(100vh - 104px); padding: 20px; ">
    <div class="dashboard-container"
         style=" padding: 20px 25px 10px;  ">
      <div
          style="line-height: 16px; flex-wrap: wrap;   align-items: center;  font-size: 16px; font-family: Source Han Sans CN;font-weight: bold;color: #2F3745; ">
        <div class="dashboard-inner">
          客户管理
          <el-tooltip class="item" effect="dark" content="温馨提示：对应列可以通过拖动改变表格宽度" placement="top">
            <i style="position: relative; left: 6px; top: 2px;" class="header-icon el-icon-info"></i>
          </el-tooltip>
        </div>
      </div>
    </div>

    <div style="display: flex; height: calc(100% - 30px);">
      <div class="left-content" style="color: #2F3745; ">
        <tree-expansion ref="treeExpansionRef" @getCurrentNodeKey="getCurrentNodeKey" @statusChange="statusChange"/>
      </div>

      <div class="right-content" style="background: #fff; " :style="`${expansionStatus? 'width: calc(100% - 260px);' : 'width: 100%;'};
            ${expansionStatus ? 'margin-left: 10px;' : 'margin-left: 0;'} `">
        <div :style="`margin-left: 12px; margin-right: 12px; height: 100%; width: calc(100% - 24px);`">
          <common-operation-form :list="list"/>
          <el-table style="margin-top: 15px; " fit :height="windowHeight - 10"
                    @select="changeevent" ref="tableRef"
                    v-loading="table.loading" :data="table.data" border >
            <template v-for="(item, index) in table.header1">
              <el-table-column :prop="item.prop" :key="index"
                               :width="item.width || 'auto'" :align="`center`"
                               :label="item.label">
                <template slot-scope="scope">
                  <span v-if="item.prop === 'initialDebtOwed'">
                    {{keepTwoDecimalFull(scope.row[item.prop])}}
                  </span>
                  <span v-else-if="item.prop === 'defaultCustomer'" style=" ">
                    {{ scope.row[item.prop] ? '是' : '否' }}
                  </span>
                  <span v-else style=" ">
                    {{ item.keepTwoDecimal ? keepTwoDecimalFull(scope.row[item.prop]) : scope.row[item.prop] }}
                  </span>
                </template>
              </el-table-column>
            </template>

            <!--            <el-table-column :align="`center`" :key="101" type="selection" :label="'禁用'" width="45"></el-table-column>-->

            <template v-for="(item, index) in table.header2">
              <el-table-column :prop="item.prop" :key="index + 1000"
                               :width="item.width || 'auto'" :align="`center`"
                               :label="item.label">
                <template slot-scope="scope">
                  <span style=" ">{{ scope.row[item.prop] }}</span>
                </template>
              </el-table-column>
            </template>

            <el-table-column
                label="操作" width="100" fixed="right">
              <template slot-scope="scope">
                <div style="display: flex;">
                  <el-tooltip content="编辑" slot="reference" placement="top">
                    <el-button size="mini" type="primary" icon="el-icon-edit" circle
                               @click="edit(scope.row)"></el-button>
                  </el-tooltip>
                  <el-tooltip content="删除" slot="reference" placement="top">
                    <el-button size="mini" @click="del(scope.row)" type="danger" icon="el-icon-delete"
                               circle></el-button>
                  </el-tooltip>
                </div>
              </template>
            </el-table-column>
          </el-table>

          <el-pagination style="position: relative; text-align: right; margin-top: 10px;"
                         :current-page="page.pageNumber"
                         layout="sizes, jumper, prev, pager, next" :page-size="page.pageSize"
                         :total="page.total">
          </el-pagination>
        </div>
      </div>
    </div>

    <el-dialog style="margin-top: 10px;"
               :close-on-click-modal="false"
               width="600px" v-dialog-drag
               title="编辑商品" :modal="false" :before-close="() => cancel(false)"
               custom-class="dialoginter3"
               :visible.sync="editDialog">
      <div>
        <common-dialog-form v-if="editDialog" ref="commondialogformref" :col="dialog.col" :list="dialog.form"/>
      </div>


      <span slot="footer" class="dialog-footer">
          <el-button size="small" @click="cancel(false)">关闭</el-button>
          <el-button type="primary" size="small" @click="submit">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import CommonOperationForm from "@/components/CommonOperationForm/index.vue";
import CommonDialogForm from "@/components/CommonDialogForm/index.vue";
import TreeExpansion from "@/components/TreeExpansion/CustomerSettings.vue";
import {addCustomer, getCustomerList, deleteCustomerByCustomerID} from "@/api/customer";
import {addUnit, getUnitList} from "@/api/unit";
import {getUserInfo} from "@/utils/auth";
import {deepClone, keepTwoDecimalFull} from "../../utils";

export default {
  name: 'product_manager',
  components: {CommonOperationForm, CommonDialogForm, TreeExpansion},
  data() {
    return {
      list: [
        {
          type: 'input',
          text: '客户名称：',
          width: '75px',
          value: '',
        },
        {
          type: 'input',
          text: '客户编号：',
          width: '75px',
          value: '',
        },
        {
          type: 'button',
          buttonIcon: 'el-icon-search',
          buttonText: '搜索',
          event: () => {
            this.pageNumber = 1;
            this.getCustomerList();
          }
        },
        {
          type: 'button',
          buttonIcon: 'el-icon-folder-add',
          buttonText: '增加',
          event: () => {
            this.editDialog = true;
            this.dialog.chooseItem = null;
          }
        },
        {
          type: 'button',
          buttonIcon: 'el-icon-document-add',
          buttonText: '导入',
          event: () => {

          }
        },
        {
          type: 'button',
          buttonIcon: 'el-icon-takeaway-box',
          buttonText: '导出',
          event: () => {

          }
        },
      ],
      expansionStatus: true,
      treeCurrentNodeKey: '',
      editDialog: false,
      table: {
        data: [],
        loading: false,
        header1: [
          {"label": "客户名称", "prop": "customerName", width: '160px',},
          {"label": "客户编号", "prop": "customerID"},
          {"label": "客户类型", "prop": "customerType"},
          {"label": "联系人", "prop": "contactPerson"},
          {"label": "联系电话", "prop": "contactNumber"},
          {
            "label": "应收欠款", "prop": "receivableAmount",
            keepTwoDecimal: true,
          },
          {"label": "联系地址", "prop": "address"},
          {"label": "默认客户", "prop": "defaultCustomer"},
        ],
        header2: [
          {
            prop: "remarks",
            label: "备注"
          }],
      },
      dialog: {
        col: 2,
        form: [
          [
            {
              text: '客户名称：',
              required: true,
              field: 'customerName',
              width: '90px',
              requiredMessage: "请输入客户名称",
              type: 'input',
              value: null,
            },
            {
              text: '客户分类：',
              width: '90px',
              field: 'customerCategory',
              requiredMessage: "请选择分类",
              type: 'selectTreeCustomer',
              node: null,
              value: null,
            },
          ],
          [
            {
              text: '客户编号：',
              type: 'input',
              width: '90px',
              field: 'customerID',
              value: '',
            },
            {
              text: '期初欠款：',
              field: 'initialDebtOwed',
              width: '90px',
              inputWidth: '100%',
              type: 'inputnumber',
              value: undefined,
              keepDecimal: 2,
              changeEvent: () => {

              },
            },
          ],
          [
            {
              text: '联系人：',
              field: 'contactPerson',
              width: '90px',
              type: 'input',
              value: null,
            },
            {
              text: '联系电话：',
              type: 'input',
              width: '90px',
              field: 'contactNumber',
              value: '',
            },
          ],
          [
            {
              text: '客户地址：',
              value: '',
              width: '90px',
              rowWidth: '100%',
              field: 'SupplierAddress',
              type: 'input',
            },
          ],
          [
            {
              text: '填写备注：',
              value: '',
              width: '90px',
              rowWidth: '100%',
              field: 'remarks',
              type: 'textarea',
            },
          ],
          [
            {
              text: '默认客户',
              value: '',
              width: '90px',
              rowWidth: '100%',
              field: 'defaultCustomer',
              type: 'checkbox',
            },
          ],
        ],
        copyForm: [
          [
            {
              text: '客户名称：',
              required: true,
              field: 'customerName',
              width: '90px',
              requiredMessage: "请输入客户名称",
              type: 'input',
              value: null,
            },
            {
              text: '客户分类：',
              width: '90px',
              field: 'customerCategory',
              requiredMessage: "请选择分类",
              type: 'selectTreeCustomer',
              node: null,
              value: null,
            },
          ],
          [
            {
              text: '客户编号：',
              type: 'input',
              width: '90px',
              field: 'customerID',
              value: '',
            },
            {
              text: '期初欠款：',
              field: 'initialDebtOwed',
              width: '90px',
              inputWidth: '100%',
              type: 'inputnumber',
              value: undefined,
              keepDecimal: 2,
              changeEvent: () => {

              },
            },
          ],
          [
            {
              text: '联系人：',
              field: 'contactPerson',
              width: '90px',
              type: 'input',
              value: null,
            },
            {
              text: '联系电话：',
              type: 'input',
              width: '90px',
              field: 'contactNumber',
              value: '',
            },
          ],
          [
            {
              text: '客户地址：',
              value: '',
              width: '90px',
              rowWidth: '100%',
              field: 'SupplierAddress',
              type: 'input',
            },
          ],
          [
            {
              text: '填写备注：',
              value: '',
              width: '90px',
              rowWidth: '100%',
              field: 'remarks',
              type: 'textarea',
            },
          ],
          [
            {
              text: '默认客户',
              value: '',
              width: '90px',
              rowWidth: '100%',
              field: 'defaultCustomer',
              type: 'checkbox',
            },
          ],
        ],
        chooseItem: null,
      },
      page: {
        pageSize: 10,
        pageNumber: 1,
        total: 0,
      }
    }
  },
  watch: {
    editDialog() {
      if (this.editDialog) {
        this.getUnitList(); // 单位
      }
    }
  },
  mounted() {
  },
  methods: {
    keepTwoDecimalFull,
    getCustomerList() {
      if (this.table.loading)
        return;
      this.table.loading = true;
      getCustomerList({
        userID: getUserInfo().userID,
        pageSize: this.page.pageSize,
        pageNumber: this.page.pageNumber,
        customerName: this.list[0].value,
        customerNumber: this.list[1].value,
        customerCategoryID: this.treeCurrentNodeKey
      }).then(res => {
        console.log(res);
        this.table.data = res.data.data;
        this.page.total = res.data.page.totalDocuments;
        this.table.loading = false;
      });
    },
    getUnitList() {
      getUnitList({
        userID: getUserInfo().userID,
      }).then(res => {
        console.log(this.dialog.form[2][0]);
        let data = res.data.data;
        let arr = [];
        for (let i = 0; i < data.length; i++) {
          arr.push({
            label: data[i].unit,
            value: data[i].unit,
          });
        }
        this.dialog.form[2][0].options = arr;
        this.dialog.copyForm[2][0].options = arr;
      });
    },
    statusChange(v) {
      console.log(v);
      this.expansionStatus = v;
      this.$refs.tableRef.doLayout();
    },
    getCurrentNodeKey(v) {
      console.log(v);
      this.treeCurrentNodeKey = v;
      this.getCustomerList();
    },
    edit(item) {
      let setData = () => {
        for (const inputSet of this.dialog.form) {
          for (const inputItem of inputSet) {
            if (inputItem['field'] === 'customerCategory') {
              inputItem['node'] = item[inputItem['field'] + 'Label'];
            }

            inputItem['value'] = item[inputItem['field']];
          }
        }
      }

      setData();
      this.dialog.chooseItem = item;
      this.editDialog = true;
    },
    del(item) {
      this.$confirm('您确认要删除该客户吗?', '提示', {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning'
      }).then(() => {
        console.log(item);
        deleteCustomerByCustomerID({
          _id: item._id
        }).then(res => {
          this.$message.success("操作成功");
          this.getCustomerList();
        });
      }).catch(() => {

      });
    },
    changeevent(selection, row) {
      console.log(selection, row);

    },
    reloadTree() {
      this.$refs.treeExpansionRef.getCustomerCategory(false);
    },
    cancel(reload = true) {
      this.editDialog = false;
      if (reload) {
        this.reloadTree();
      }
      this.dialog.form = deepClone(this.dialog.copyForm);
      console.log( this.dialog.form);
    },
    submit() {
      let data = this.$refs.commondialogformref.requiredEmpty();
      if (data) {
        this.$message.error(data.requiredMessage);
        return;
      }

      data = this.$refs.commondialogformref.getData();
      data['isDisabled'] = false;
      console.log(data, getUserInfo());

      // 提交data
      data["userID"] = getUserInfo().userID;
      if (this.dialog.chooseItem) {
        data['_id'] = this.dialog.chooseItem['_id'];
      }
      addCustomer(data).then(res => {
        console.log(res);
        this.dialog.form = deepClone(this.dialog.copyForm);
        // this.getCustomerList();
        this.reloadTree();
        this.editDialog = false;
        this.$message.success("操作成功");
      });
    }
  }
}
</script>


<style lang="scss">
.dashboard {
  &-container {
    background: #fff;
    box-shadow: 0px 0px 10px 0px rgba(45, 51, 65, 0.08);
    border-radius: 10px;
  }

  &-text {
    font-size: 30px;
    line-height: 46px;
  }
}

.dashboard-inner {
  font-size: 16px;
  font-weight: 700;
  padding: 0 0 10px 0;
  color: #2f3745;
}


.el-scrollbar__view {
  height: 100%;
}

.el-scrollbar__wrap {
  overflow: scroll;
}

.box-card .el-card__body {
  height: 100%;
}

.left-content {
  line-height: 16px;
  flex-wrap: wrap;
  border-radius: 10px;
  display: flex;
  padding-top: 10px;
  align-items: center;
  font-size: 16px;
  font-family: Source Han Sans CN;
  font-weight: bold;
}


.right-content {
  line-height: 16px;
  flex-wrap: wrap;
  width: calc(100% - 260px);
  border-radius: 10px;
  display: flex;
  padding-top: 10px;
  margin-top: 10px;
  margin-left: 10px;
  align-items: center;
  font-size: 16px;
  font-family: Source Han Sans CN;
  font-weight: bold;
}
</style>
